package com.zhi.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.zhi.shiro.UserRealm;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

	/**
     * shiro 登录路径控制
     */
	@Bean
	public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);

		// 当此用户是一个非认证用户,需要先登陆进行认证
		shiroFilterFactoryBean.setLoginUrl("/login");// 登录页面
		shiroFilterFactoryBean.setSuccessUrl("/index");// 成功页面
		shiroFilterFactoryBean.setUnauthorizedUrl("/403");// 授权拦截返回页面

		// 下边表示允许匿名访问的文件夹,前面为固定的文件夹的路径
		Map<String, String> fMap = new HashMap<>();
		// anon表示允许匿名访问
		fMap.put("/login", "anon");
		fMap.put("/register","anon");
		fMap.put("/getVerify", "anon");
		fMap.put("/css/**", "anon");
		fMap.put("/js/**", "anon");
		fMap.put("/fonts/**", "anon");
		fMap.put("/img/**", "anon");

		// "logout"表示退出
		fMap.put("/logout", "logout");

		// 拦截页面，必须授权才能访问
		fMap.put("/**", "authc");

		shiroFilterFactoryBean.setFilterChainDefinitionMap(fMap);
		return shiroFilterFactoryBean;
	}

	/**
	 * 引入UserRealm登录逻辑
	 */
	@Bean
	public UserRealm userRealm() {
		return new UserRealm();
	}
	
	/**
     * shiro session的管理
     */
	@Bean
	public SecurityManager securityManager() {
		DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
		defaultWebSecurityManager.setRealm(userRealm());
		defaultWebSecurityManager.setSessionManager(sessionManager());
		return defaultWebSecurityManager;
	}
	
	/**
     * shiro session的超时设置
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(18000 * 1000);//超时时间30分钟
        sessionManager.setSessionDAO(new MemorySessionDAO());
        return sessionManager;
        
    }

}
